<template>
  <view class="common-header-bg">
    <view class="header-tab" :style="{paddingTop: (useAppData.titleHeight+3) + 'px'}">
      <view class="header-item" @tap="gotoChat">对话</view>
      <view class="header-item" @tap="gotoGroup">跑团</view>
      <view class="header-item-active">我的</view>
    </view>
    <view class="user-info">
      <view class="icon-avart">
        <image class="icon" :src="state.userInfo?.customers?.headUrl || 'https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/avart-wu.png'"></image>
      </view>
      <view class="user-con">
        <text @tap="gotoLogin">{{state?.token ? state.userInfo?.maskMobile : "请点击登录"}}</text>
        <text class="user-id" v-if="state.token">ID: {{state.userInfo?.customers?.customerId}}</text>
      </view>
    </view>
    <view style="padding-top: 15px">
      <uni-list>
        <uni-list-item v-for="(item, index) in state.list" :key="index" showArrow :title="item.name" :rightText="item.rightText" @tap="gotoPage(item)"/>
      </uni-list>
    </view>
    <button v-if="state.token" class="confirm-btn" @tap="handleLogout">账号退出</button>
  </view>
</template>

<script setup>
  import { onLaunch, onLoad, onShow, onHide, onUnload, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
  import { reactive, onMounted } from "vue"
  import { storeToRefs } from "pinia";
  import { useAppStore } from "../../store/app";
  import { useCommonStore } from "../../store/common";
  import { userLoginStore } from "../../store/userLogin"
  import { useShareStore } from "../../store/share";
  import { useGroupStore } from "../../store/group"
  import * as util from "../../utils/util"
  import * as API from "../../api/api"
  import {useRunInfoStore} from "@/store/runInfo";
  const useShareData = useShareStore()
  const useAppData = useAppStore()
  const useCommonData = useCommonStore()
  const userLoginData = userLoginStore()
  const useRunInfoData = useRunInfoStore();
  const useGroupData = useGroupStore()
  const {userInfo} = storeToRefs(userLoginData)
  const state = reactive({
    userInfo: null,
    list: [
      {
        name: "开始跑步",
        url: "/pages/index/index",
        key: "RUN"
      },
      {
        name: "个人资料",
        url: "/pages/personInfo/personInfo"
      },
      {
        name: "里程记录",
        url: "/pages/record/record"
      },
      {
        name: "我的体检",
        url: "/examPages/exam/exam"
      },
      {
        name: "运动报告",
        url: "/sportPages/sports/report"
      },
      {
        name: "功能反馈",
        url: "/examPages/feedback/feedback"
      },
      {
        name: "健康福利一分GO",
        rightText: "小程序",
        appId: "wx5a128f1216bbb3b3", // wx78b581ee599da2b1
        path: "/pages/home/index"
      },
      {
        name: "运动健康好物分享",
        custom: true,
        rightText: "小程序",
        appId: "wx5a128f1216bbb3b3", // wx78b581ee599da2b1
        path: "/pages/appointment/mall/goodsList/goodsList?shopId=10015&categoryId=10072"
      },
    ],
    show: false,
    token: null,
    isLogout: false
  })

  onShareAppMessage((res) => {
    return useShareData.shareInfo
  })
  onShareTimeline((res) => {
    return useShareData.shareInfo
  })

  const handleLogout = () => {
    console.log("退出登录")
    // useRunInfoData.setPopupExpire('')
    if (state.isLogout) return
    onLogout()
  }

  const onLogout = () => {
    state.isLogout = true
    API.userLogout().then(res => {
      if (res.code === 0) {
        uni.showToast({
          title: "退出成功",
          icon: "none"
        })
        uni.clearStorageSync()
        useRunInfoData.stopCountDown()
        useRunInfoData.resetAll()
        useGroupData.resetAll()
        setTimeout(() => {
          uni.redirectTo({
            url: "/pages/chat/chat"
          });
          state.isLogout = false
        }, 1500)
      } else {
        uni.showToast({
          title: res.message || "退出失败",
          icon: "none"
        })
        state.isLogout = false
      }
    }).catch(err => {
      state.isLogout = false
      uni.showToast({
        title: err || "退出失败",
        icon: "none"
      })
    })
  }

  const gotoGroup = () => {
		uni.reLaunch({
		  url: "/runGroupPages/index/index",
		});
	}

  const gotoLogin = () => {
    if (!state.token)
    uni.navigateTo({
      url: `/pages/login/login`,
    });
  }


  const gotoChat = () => {
    uni.reLaunch({
      url: "/pages/chat/chat"
    });
  }

  const gotoPage = (item) => {
    if (!state.token) {
      uni.showToast({
        title: "请先登录，再继续其他功能使用",
        icon: "none"
      })
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/login/login`,
        });
      }, 1000)
      return
    }
    let prePage="/pages/me/me"
    if (item.key === "RUN") {
      uni.reLaunch({
        url: `/pages/index/index?prePage=${prePage}`,
      });
    } else {
      if (item.url) {
        useRunInfoData.setInitReportType("day")
        uni.navigateTo({
          url: item.url
        });
      }
      if (item.appId) {
        useCommonData.getBizParam().then(res => {
          useCommonData.gotoMiniProgram({appId: item.appId});
        })
      }
      if (item.appId && item.custom) {
        uni.navigateToMiniProgram({
          appId: item.appId,
					path: item.path,
          extraData: {},
          envVersion: "release",  // 跳转的版本：develop（开发版），trial（体验版），release（正式版）
          success(res) {
            console.log("跳转成功", res)
          },
          fail(res) {
            console.log("跳转失败", res)
          }
        })
      }
    }
  }

  onShow(() => {
    state.token = uni.getStorageSync("token") || null
    state.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
  })
</script>

<style lang="scss" scoped>
  .user-info{
    font-weight: 500;
    font-size: 36rpx;
    color: #222222;
    padding: 30rpx 0 0 32rpx;
    display: flex;
    align-items: center;
    .icon-avart{
      width: 116rpx;
      height: 116rpx;
      margin-right: 24rpx;
      border-radius: 16rpx;
      overflow: hidden;
      .icon{
        width: 100%;
        height: 100%;
      }
    }
    .user-con{
      display: flex;
      flex-direction: column;
      .user-id{
        font-size: 28rpx;
        color: rgba(34,34,34,0.7);
      }
    }
  }
  .confirm-btn {
    width: calc(100vw - 68rpx);
    height: 88rpx;
    background: #fff;
    border-radius: 44rpx;
    color: #08CB8F;
    border: 2rpx solid #08CB8F;
    position: fixed;
    bottom: 84rpx;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9;
  }
</style>
